import javax.swing.*;
import java.awt.Color;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class ToggleButtonExample implements  ItemListener{

    // Definition of global values and items that are part of the GUI.

    JToggleButton toggleButton;
    JPanel totalGUI;

    public JPanel createContentPane (){

        // We create a bottom JPanel to place everything on.
        totalGUI = new JPanel();
        totalGUI.setBackground(Color.red);
        totalGUI.setLayout(null);

        toggleButton = new JToggleButton("Off");
        toggleButton.setLocation(75,10);
        toggleButton.setSize(100,100);
        toggleButton.addItemListener(this);
        totalGUI.add(toggleButton);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // This is the new itemStateChanged Method.
    // It catches any events with an ItemListener attached.
    // Using an if statement, we can determine if the button is now selected or deselected
	// after the action and perform changes to the GUI accordingly.

    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED)
        {
            toggleButton.setText("On!");
            totalGUI.setBackground(Color.green);
        }
        else
        {
            toggleButton.setText("Off");
            totalGUI.setBackground(Color.red);
        } 
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JToggleButton [=]");

        //Create and set up the content pane.
        ToggleButtonExample demo = new ToggleButtonExample();
        frame.setContentPane(demo.createContentPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 150);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}